package com.seecen.day03;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class MyJpanel extends JPanel
        implements Runnable,
        KeyListener {
    public int x=500;
    public int y=650;
    public static boolean UP = false;
    public static boolean DOWN = false;
    public static boolean LEFT = false;
    public static boolean RIGHT = false;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        this.setBackground(Color.BLACK);
        //画个圆
        g.setColor(Color.RED);
        g.fillOval(x,y,100,100);

    }


    @Override
    public void keyTyped(KeyEvent e) {

    }


    //键盘按压触发
    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()){
            case KeyEvent.VK_LEFT:
                LEFT = true;
                break;
            case KeyEvent.VK_RIGHT:
                RIGHT = true;
                break;
            case KeyEvent.VK_UP:
                UP = true;
                break;
            case KeyEvent.VK_DOWN:
                DOWN = true;
                break;
        }

    }


    //键盘释放触发
    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()){
            case KeyEvent.VK_LEFT:
                LEFT = false;
                break;
            case KeyEvent.VK_RIGHT:
                RIGHT = false;
                break;
            case KeyEvent.VK_UP:
                UP = false;
                break;
            case KeyEvent.VK_DOWN:
                DOWN = false;
                break;
        }
    }



    @Override
    public void run() {
        while (true){
            if (UP){
                y--;
            }
            if (DOWN){
                y++;
            }
            if(LEFT){
                x--;
            }
            if (RIGHT){
                x++;
            }
            try {
                Thread.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            repaint();
        }

    }
}
